/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.facilscrum.form.tareas;

import javax.swing.table.DefaultTableModel;
import org.facilscrum.beans.Equiposusuarios;
import org.javscaz.javscaztools.utilidades.Utilidades;
import org.facilscrum.beans.Tareas;
import org.facilscrum.beans.Userstories;
import org.facilscrum.beans.Usuarios;
import org.facilscrum.controller.EquiposusuariosController;
import org.facilscrum.controller.TareasController;
import org.facilscrum.controller.UserstoriesController;
import org.facilscrum.controller.UsuariosController;
import org.facilscrum.generales.Mensajeria;
import org.facilscrum.sesion.MySesion;

/**
 *
 * @author avbravo
 */
public class TaskInformesForm extends javax.swing.JInternalFrame {
  EquiposusuariosController equiposusuariosController = new EquiposusuariosController();
    Tareas tareas = new Tareas();
    TareasController tareasController = new TareasController();
    UserstoriesController userstoriesController = new UserstoriesController();
    Userstories userstories = new Userstories();
    UsuariosController usuariosController = new UsuariosController();
    Usuarios usuarios = new Usuarios();
    DefaultTableModel modelo;

    /**
     * Creates new form BacklogForm
     */
    public TaskInformesForm() {
        initComponents();
        modelo = (DefaultTableModel) jTable1.getModel();
        jTable1.setEnabled(true);
    
        cargarTablaTareas();
        if ( !cargarComboUserStories()) {
           
            jTable1.setEnabled(false);
        }
        if (!MySesion.getSeleccionoProyectoTrabajo()) {
            Mensajeria.MensajeWarning("Debe indicar el proyecto de trabajo");
        } else {
          
            jTextFieldProyecto.setText(MySesion.getProyectos().getProyecto());
        }
        cargarTablaTareas();
        limpiar();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButtonCerrar = new javax.swing.JButton();
        jButtonEliminar = new javax.swing.JButton();
        jTextFieldProyecto = new javax.swing.JTextField();
        jComboBoxUserstories = new javax.swing.JComboBox();
        jLabel8 = new javax.swing.JLabel();

        setClosable(true);
        setTitle("Informes de Tareas");

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Proyecto");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "id", "Tarea", "Duracion", "Estatus", "usuario"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Object.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(0).setMaxWidth(60);
        jTable1.getColumnModel().getColumn(2).setMaxWidth(100);

        jButtonCerrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/avbravo/jscrum/gif/return.gif"))); // NOI18N
        jButtonCerrar.setToolTipText("Cerrar");
        jButtonCerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCerrarActionPerformed(evt);
            }
        });

        jButtonEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/avbravo/jscrum/gif/print.png"))); // NOI18N
        jButtonEliminar.setToolTipText("Eliminar");
        jButtonEliminar.setEnabled(false);
        jButtonEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonEliminarActionPerformed(evt);
            }
        });

        jTextFieldProyecto.setEnabled(false);

        jComboBoxUserstories.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxUserstoriesActionPerformed(evt);
            }
        });

        jLabel8.setText("User Stories");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(18, 18, 18)
                                .addComponent(jTextFieldProyecto, javax.swing.GroupLayout.PREFERRED_SIZE, 374, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 131, Short.MAX_VALUE))))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel8)
                                .addGap(24, 24, 24)
                                .addComponent(jComboBoxUserstories, javax.swing.GroupLayout.PREFERRED_SIZE, 360, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addGap(204, 204, 204)
                                .addComponent(jButtonEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jButtonCerrar, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextFieldProyecto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBoxUserstories, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(38, 38, 38)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButtonEliminar)
                    .addComponent(jButtonCerrar))
                .addContainerGap(33, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCerrarActionPerformed
        dispose();
    }//GEN-LAST:event_jButtonCerrarActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        try {
            Integer fila = jTable1.getSelectedRow();
            if (fila == -1) {
                Mensajeria.Mensaje("No se selecciono ninguna fila");

                return;
            }
            tareas.setIdtarea(Integer.parseInt(jTable1.getValueAt(fila, 0).toString()));
           Tareas t = tareasController.findByPrimaryKey(tareas);
            if (t != null) {
              tareas = t;
            } else {
                Mensajeria.MensajeWarning("No existe una tarea con ese codigo");
                limpiar();
                return;
            }
           
            Usuarios u = new Usuarios();
            u.setUsername(tareas.getUsername());
            u = usuariosController.findByPrimaryKey(u);
  
            jButtonEliminar.setEnabled(true);
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "MouseClicked()");
        }
    }//GEN-LAST:event_jTable1MouseClicked

    private void jButtonEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEliminarActionPerformed
        
    }//GEN-LAST:event_jButtonEliminarActionPerformed

    private void jComboBoxUserstoriesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxUserstoriesActionPerformed
         try {
            
            int j = jComboBoxUserstories.getSelectedIndex();
            if (j != -1) {
                userstories = userstoriesController.getUserstorieslist().get(j);
                tareas.setIduserstories(userstories.getIduserstories());
                cargarTablaTareas();
            } else {
                Mensajeria.Mensaje("No se ha seleccionado ningun user stories");
                
            }
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "combo()");
        }
    }//GEN-LAST:event_jComboBoxUserstoriesActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonCerrar;
    private javax.swing.JButton jButtonEliminar;
    private javax.swing.JComboBox jComboBoxUserstories;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextFieldProyecto;
    // End of variables declaration//GEN-END:variables

    
     private Boolean cargarComboUserStories() {
        try {
            
            jComboBoxUserstories.removeAllItems();
            String where  = "idproyecto='"+MySesion.getProyectos().getIdproyecto()+"'";
            if (userstoriesController.query(where)) {
                jComboBoxUserstories.removeAllItems();
                for (Userstories u : userstoriesController.getUserstorieslist()) {
                    jComboBoxUserstories.addItem(u.getIduserstories() + " " + u.getNombre());
                }
                return true;
            } else {
                Mensajeria.Mensaje("Debe crear primero los user stories ");
            }
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "cargarComboUserStories()");
            
        }
        return false;
    }
    /*
     * 
     */

    private Boolean guiToData() {
        try {

            
         
            
//            tareas.setDuracion(Integer.parseInt(jTextFieldDuraccion.getText()));
//            tareas.setDescripcion(jTextAreaDescripcion.getText());
//            tareas.setEstatus("asignado");
//            tareas.setFecha(MySesion.getFechausername());
//            tareas.setTask(jTextFieldTarea.getText());
//            int j = jComboBoxUserstories.getSelectedIndex();
//            if (j != -1) {
//                Userstories u = userstoriesController.getUserstorieslist().get(j);
//                tareas.setIduserstories(u.getIduserstories());
//            } else {
//                Mensajeria.Mensaje("No se ha seleccionado ningun user stories");
//                return false;
//            }
//            int k = jComboBoxUsuarios.getSelectedIndex();
//            if (k != -1) {
//                //  Usuarios usuarios = usuariosController.getUsuarioslist().get(k);
//                Equiposusuarios e = equiposusuariosController.getEquiposusuarioslist().get(k);
//                tareas.setUsername(e.getUsername());
//            } else {
//                Mensajeria.Mensaje("No se ha seleccionado ningun usuario");
//                return false;
//            }
            
            return true;
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "actualizar()");

        }
        return false;
    }

 

  

   private void cargarTablaTareas() {
        try {
            
            modelo = Utilidades.limpiarModelo(modelo);
            String where = "iduserstories='" + userstories.getIduserstories() + "'";
                      if (tareasController.query(where)) {
                for (Tareas t : tareasController.getTareaslist()) {
                    Object[] filas = new Object[5]; // Hay tres columnas en la tabla       
                    filas[0] = t.getIdtarea();
                    filas[1] = t.getTask();
                    filas[2] = t.getDuracion();
                    filas[3] = t.getEstatustareas().getEstatustareas();
                    filas[4] = t.getUsuarios().getUsername();
                    modelo.addRow(filas);                  
                }                
            } 
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "cargarTablaTareas()");
        }
    }

    private void limpiar() {
      
        jButtonEliminar.setEnabled(false);
    }
}
